'use strict';
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const o = require('./nodes/identity.cjs'),
  $ = require('./public-api.cjs'),
  g = require('./visit.cjs'),
  A = {
    BLOCK_FOLDED: '>',
    BLOCK_LITERAL: '|',
    PLAIN: ':',
    QUOTE_DOUBLE: '"',
    QUOTE_SINGLE: "'",
  };
function E(e, i) {
  let c = !1;
  return (
    g.visit(e, {
      Value(t, s) {
        if (s.anchor === i) return (c = !0), g.visit.BREAK;
      },
    }),
    c
  );
}
function S(e) {
  const i = $.parseAllDocuments(e),
    c = i.find(a => a.errors.length > 0),
    t = c ? c.errors[0].message : null,
    s = ['+STR'];
  try {
    for (let a = 0; a < i.length; ++a) {
      const r = i[a];
      let l = r.contents;
      Array.isArray(l) && (l = l[0]);
      const [u] = r.range || [0],
        n = r.errors[0];
      if (n && (!n.pos || n.pos[0] < u)) throw new Error();
      let f = '+DOC';
      if (r.directives.docStart) f += ' ---';
      else if (
        r.contents &&
        r.contents.range[2] === r.contents.range[0] &&
        !r.contents.anchor &&
        !r.contents.tag
      )
        continue;
      s.push(f), p(s, r, (n == null ? void 0 : n.pos[0]) ?? -1, l);
      let h = '-DOC';
      r.directives.docEnd && (h += ' ...'), s.push(h);
    }
  } catch (a) {
    return { events: s, error: t ?? a };
  }
  return s.push('-STR'), { events: s, error: t };
}
function p(e, i, c, t) {
  if (!t) {
    e.push('=VAL :');
    return;
  }
  if (c !== -1 && o.isNode(t) && t.range[0] >= c) throw new Error();
  let s = '',
    a = o.isScalar(t) || o.isCollection(t) ? t.anchor : void 0;
  if (a) {
    if (/\d$/.test(a)) {
      const r = a.replace(/\d$/, '');
      E(i, r) && (a = r);
    }
    s = ` &${a}`;
  }
  if ((o.isNode(t) && t.tag && (s += ` <${t.tag}>`), o.isMap(t))) {
    const r = t.flow ? '+MAP {}' : '+MAP';
    e.push(`${r}${s}`),
      t.items.forEach(({ key: l, value: u }) => {
        p(e, i, c, l), p(e, i, c, u);
      }),
      e.push('-MAP');
  } else if (o.isSeq(t)) {
    const r = t.flow ? '+SEQ []' : '+SEQ';
    e.push(`${r}${s}`),
      t.items.forEach(l => {
        p(e, i, c, l);
      }),
      e.push('-SEQ');
  } else if (o.isPair(t))
    e.push(`+MAP${s}`), p(e, i, c, t.key), p(e, i, c, t.value), e.push('-MAP');
  else if (o.isAlias(t)) {
    let r = t.source;
    if (r && /\d$/.test(r)) {
      const l = r.replace(/\d$/, '');
      E(i, l) && (r = l);
    }
    e.push(`=ALI${s} *${r}`);
  } else {
    const r = A[String(t.type)];
    if (!r) throw new Error(`Unexpected node type ${t.type}`);
    const l = t.source
      .replace(/\\/g, '\\\\')
      .replace(/\0/g, '\\0')
      .replace(/\x07/g, '\\a')
      .replace(/\x08/g, '\\b')
      .replace(/\t/g, '\\t')
      .replace(/\n/g, '\\n')
      .replace(/\v/g, '\\v')
      .replace(/\f/g, '\\f')
      .replace(/\r/g, '\\r')
      .replace(/\x1b/g, '\\e');
    e.push(`=VAL${s} ${r}${l}`);
  }
}
exports.testEvents = S;
